package Re;

import java.util.PriorityQueue;

class MytimerTask implements Comparable<MytimerTask>{
   private  Runnable runnable;
   private long time;
    public MytimerTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public long gettime(){
        return time;
    }
    public Runnable getrun(){
        return runnable;
    }
    @Override
    public int compareTo(MytimerTask o) {
        return (int) (this.time-o.time);
    }
}
public class MyTimer {
    Object locker=new Object();
    PriorityQueue<MytimerTask> queue=new PriorityQueue<>();
   public void schedule(Runnable runnable,long time){
       synchronized (locker){
           MytimerTask mytimerTask=new MytimerTask(runnable,time);
           queue.offer(mytimerTask);
           locker.notify();
       }
   }
   public MyTimer(){
       Thread t=new Thread(()->{
           while (true){
               try {
                   synchronized (locker){
                       while (queue.isEmpty()){
                           locker.wait();
                       }
                       MytimerTask top=queue.peek();
                       long CurTime=System.currentTimeMillis();
                       if (CurTime>=top.gettime()){
                           top.getrun().run();
                           queue.poll();
                       }else {
                           locker.wait(top.gettime()-CurTime);
                       }
                   }
               }catch (InterruptedException e){
                   e.printStackTrace();
               }

           }
       });
       t.start();
   }

}
class Main{
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
    }
}